﻿namespace ApiTemplate.Common
{
    /// <summary>
    /// 操作office相关帮助类
    /// </summary>
    public partial class OfficelHelper
    {
        /// <summary>
        /// 导出Word到本地目录
        /// </summary>
        /// <param name="apitemplatePath">模板路径</param>
        /// <param name="savePath">要保存的路径</param>
        /// <param name="keyList">模板中域的名称集合</param>
        /// <param name="valList">模板中域的值（顺序和域名称统一）</param>
        /// <param name="tables">注意tableName必须和模板中的域名称一直</param>
        /// <returns>生成后的文件路径</returns>
        public static string ExportWordForLocal(string apitemplatePath, string savePath, string[] keyList, object[] valList, IEnumerable<DataTable> tables = null)
        {
            Document doc = new(apitemplatePath);
            doc.MailMerge.Execute(keyList, valList);

            #region 处理需要循环的数据
            if (tables != null && tables.Count() > 0)
            {
                foreach (var table in tables)
                {
                    doc.MailMerge.ExecuteWithRegions(table);
                }
            }
            #endregion
            doc.Save(savePath);
            return savePath;
        }

        /// <summary>
        /// 读取数据到集合中
        /// </summary>
        /// <typeparam name="T">返回的类型</typeparam>
        /// <param name="excelPath">excel的路径</param>
        /// <param name="startCell">从哪个单元格开始读取</param>
        /// <returns>读取到的数据集合</returns>
        public static IEnumerable<T> ReadDataFromExcel<T>(string excelPath, string startCell = "A1") where T : class, new()
        {
            return MiniExcel.Query<T>(excelPath, startCell);
        }

        /// <summary>
        /// 直接导出
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="excelPath">要生成的文件名；如：C:\学生信息.xlsx</param>
        /// <returns></returns>
        public static string ExportExcel(object datas, string excelPath)
        {
            FileHelper.FileDel(excelPath);
            MiniExcel.SaveAs(excelPath, datas);
            return excelPath;
        }

        /// <summary>
        /// 从模板生成
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="excelName">要生成的文件名；如：C:\学生信息.xlsx</param>
        /// <param name="apitemplateName">模板物理路径；如：C:\学生信息.xlsx</param>
        /// <returns>返回OSS地址</returns>
        public static string ExportExcelFromApiTemplate(object datas, string excelName, string apitemplateName)
        {
            FileHelper.FileDel(excelName);
            MiniExcel.SaveAsByTemplate(excelName, apitemplateName, datas);
            return excelName;
        }
    }
}
